﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace MoveToPrimary {
	class Program {
		[DllImport ( "user32.dll", SetLastError = true )]
		internal static extern bool MoveWindow ( IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint );

		[DllImport ( "user32.dll" )]
		[return: MarshalAs ( UnmanagedType.Bool )]
		public static extern bool GetWindowRect ( IntPtr hwnd, out NRectangle lpRect );

		
		static void Main ( ) {
			Console.WriteLine ( "Finding Windows..." );

			TaskWindowSeeker tws = new TaskWindowSeeker ( ) {
				SkipNotVisibleWindows = true,
			};
			tws.Refresh ( );
			foreach ( var window in tws.Windows ) {
				NRectangle rect = new NRectangle ( );
				GetWindowRect ( window.Handle, out rect );

				Rectangle primary = Screen.PrimaryScreen.WorkingArea;
				Rectangle wrect = rect.ToRectangle ( );
				//Console.WriteLine ( "{0}:{1}", window.Title, wrect );
				if ( !wrect.IntersectsWith ( primary ) || wrect.Right > primary.Right + 30 ) {
					//Console.WriteLine ( "Need to move: {0}", window.Title );
					MoveWindow ( window.Handle, primary.Left, primary.Top, wrect.Width, wrect.Height, true );
				}
			}

			//Console.WriteLine ( "Press Enter to Continue..." );
			//Console.ReadLine ( );
		}
	}
}
